from scipy import ndimage
from skimage import data, util
from matplotlib import pyplot as plt 
# img为原始图像
img = data.astronaut()[:, :, 0]
# 对图像加入胡椒噪声
pepper_img = util.random_noise(img, mode='pepper',seed=None,clip=True)
# 对图像加入盐粒噪声
salt_img = util.random_noise(img, mode='salt',seed=None,clip=True)
n = 3
# 高斯滤波
gauss_img = ndimage.gaussian_filter(pepper_img, 1)
# 最大值滤波
max_img = ndimage.maximum_filter(pepper_img, (n, n))
# 最小值滤波
min_img = ndimage.minimum_filter(salt_img, (n, n))
# 显示图像
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False
plt.subplot(2, 3, 1)
plt.axis('off')
plt.imshow(img, cmap = 'gray')
plt.title('原图像')
plt.subplot(2, 3, 2)
plt.axis('off')
plt.imshow(pepper_img, cmap = 'gray')
plt.title('加胡椒噪声图像')
plt.subplot(2, 3, 3)
plt.axis('off')
plt.imshow(salt_img, cmap = 'gray')
plt.title('加盐粒噪声图像')
plt.subplot(2, 3, 4)
plt.axis('off')
plt.imshow(gauss_img, cmap = 'gray')
plt.title('高斯滤波')
plt.subplot(2, 3, 5)
plt.axis('off')
plt.imshow(max_img, cmap = 'gray')
plt.title('最大值滤波')
plt.subplot(2, 3, 6)
plt.axis('off')
plt.imshow(min_img, cmap = 'gray')
plt.title('最小值滤波')
plt.savefig('最大值和最小值滤波结果.tif')